#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
from conf import CONFIG
from logger import logger
from util.gitee_api import Gitee
from util.github_api import Github
from util.gitlab_api import Gitlab


class IssueMode:
    """
    Feedback by creating an issue
    """

    def __init__(self, cve_num, cve_platform, patch_url, issue_platform):
        self.cve_num = cve_num
        self.cve_platform = cve_platform
        self.patch_url = patch_url
        self.issue_platform = issue_platform
        self._support_issue_platform = {'gitee': Gitee,
                                        'github': Github,
                                        'gitlab': Gitlab}

    async def create_feedback_issue(self):
        """
        Create an issue about tool feedback
        :return: True or False
        """
        platform_api_class = self._support_issue_platform.get(
            self.issue_platform)
        if platform_api_class is None:
            logger.error(
                f'Issue hosting platform: {self.issue_platform} does not support')
            return False
        if not all([CONFIG.FEEDBACK_ISSUE_OWNER, CONFIG.FEEDBACK_ISSUE_REPO]):
            logger.error(
                f'"FEEDBACK_ISSUE_OWNER" or "FEEDBACK_ISSUE_REPO" no setting, Please set in file "config.ini"')
            return False

        title = f"CVE: {self.cve_num} patch information"
        description = f"Cve reference URL: {self.cve_platform}\nPatch url: {self.patch_url}"
        platform_api = platform_api_class()
        platform_api.set_attr(CONFIG.FEEDBACK_ISSUE_OWNER,
                              CONFIG.FEEDBACK_ISSUE_REPO)
        response = await platform_api.create_issue(title=title, body=description)
        return response is not None
